//
//  TempSecretKeyViewController.swift
//  WNLockDemo
//
//  Created by 裴威 on 31/08/2018.
//  Copyright © 2018 wunu. All rights reserved.
//

import UIKit
import PKHUD

class TempSecretKeyViewController: UIViewController {

    @IBOutlet weak var tempKeyWrapperView: UIView!
    @IBOutlet weak var tempKeySettingWrapperView: UIView!
    /// 临时秘钥
    @IBOutlet weak var tempKeyLabel: UILabel!
    /// 锁名称
    @IBOutlet weak var lockNameLabel: UILabel!
    /// 生效时间
    @IBOutlet weak var effectiveTimeLabel: UILabel!
    /// 有效时长
    @IBOutlet weak var effectiveDurationLabel: UILabel!
    /// 有效次数
    @IBOutlet weak var effectiveCountLabel: UILabel!
    /// 发送/接受按钮
    @IBOutlet weak var handleButton: UIButton!
    // ====
    var lock: WNLockModel?
    var tempKeyId: Int?
    var tempKeyCode: Int? {
        didSet {
            if let code = tempKeyCode {
                tempKeyLabel.text = "\(code)"
            }
        }
    }
    fileprivate var state: Int = -1
    
    override func viewDidLoad() {
        super.viewDidLoad()
        configureNavigationBarBack()
        self.navigationItem.title = "临时秘钥"
        
        tempKeyWrapperView.layer.cornerRadius = 4
        tempKeyWrapperView.layer.shadowColor = Colors(hex: 0x666666).cgColor
        tempKeyWrapperView.layer.shadowOffset = CGSize(width: 0, height: 0)
        tempKeyWrapperView.layer.shadowRadius = 10
        tempKeyWrapperView.layer.shadowOpacity = 0.5
        
        tempKeySettingWrapperView.layer.cornerRadius = 4
        tempKeySettingWrapperView.layer.shadowColor = Colors(hex: 0x666666).cgColor
        tempKeySettingWrapperView.layer.shadowOffset = CGSize(width: 0, height: 0)
        tempKeySettingWrapperView.layer.shadowRadius = 10
        tempKeySettingWrapperView.layer.shadowOpacity = 0.5
        if let keyId = self.tempKeyId {
            getTempkeyInfo(tempKeyId: keyId)
        } else {
            fetchData()
        }
    }

    private func fetchData() {
        if let id = self.lock?.id {
            WNLockApi.genTempKey(lockId: id).execute { result in
                switch result {
                case .success(let json):
                    self.tempKeyId = json["tempKeyId"].intValue
                    self.tempKeyCode = json["tempKeyCode"].intValue
                    self.getTempkeyInfo(tempKeyId: json["tempKeyId"].intValue)
                case .failure(let error):
                    HUD.flash(.label(error.errMsg), delay: 1.5)
                }
            }
        }
    }
    private func getTempkeyInfo(tempKeyId: Int) {
        WNLockApi.getTempKeyInfo(tempkeyId: tempKeyId).execute { result in
            switch result {
            case .success(let json):
                let dateFormmat = DateFormatter()
                dateFormmat.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" // 2018-03-14T06:35:57.219Z
                if let startTime = json["startTime"].string {
                    let date = dateFormmat.date(from: startTime)
                    let translateDateFmt = DateFormatter()
                    translateDateFmt.dateFormat = "生效时间: yyyy-MM-dd HH:mm"
                    let showTime = translateDateFmt.string(from: date!)
                    self.effectiveTimeLabel.text = showTime
                }
                
                // 有效时长
                let validTime = json["validTime"].intValue
                self.effectiveDurationLabel.text = "\(validTime)s"
                self.effectiveCountLabel.text = "\(json["validCount"].intValue)次"
                // 待激活状态
                let state = json["state"].intValue
                self.state = state
                if state == 1 {
                    self.handleButton.setTitle("确认", for: .normal)
                } else if state == 0 {
                    self.handleButton.setTitle("领取", for: .normal)
                }
            case .failure(let error):
                HUD.flash(.label(error.errMsg), delay: 1.5)
            }
        }
    }
    /// 填写生效时间
    @IBAction func handleInputEffectiveTimeEvent(_ sender: UITapGestureRecognizer) {
        let backgroundView = UIView(frame: self.view.bounds)
        backgroundView.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.4)
        backgroundView.isUserInteractionEnabled = true
        let tapgesture = UITapGestureRecognizer(target: self, action: #selector(handleDismissDatePickerEvent(_:)))
        backgroundView.addGestureRecognizer(tapgesture)
        backgroundView.alpha = 0
        self.view.addSubview(backgroundView)
        
        let datePicker = UIDatePicker(frame: CGRect(x: 0, y: backgroundView.bounds.height, width: backgroundView.bounds.width, height: 210))
        datePicker.addTarget(self, action: #selector(handleDataPickerValueChangedEvent(_:)), for: .valueChanged)
        datePicker.backgroundColor = UIColor.white
        datePicker.datePickerMode = .dateAndTime
        datePicker.locale = Locale(identifier: "zh_CN")
        backgroundView.addSubview(datePicker)
        
        UIView.animate(withDuration: 0.25) {
            backgroundView.alpha = 1
            datePicker.frame = CGRect(x: 0, y: backgroundView.bounds.height - 210, width: backgroundView.bounds.width, height: 210)
        }
    }
    /// 填写有效次数
    @IBAction func handleInputEffectiveCountEvent(_ sender: UITapGestureRecognizer) {
        showInputAlert(withTitle: "设置有效次数(次)") { (text) in
            self.effectiveCountLabel.text = "\(text)s"
        }
    }
    /// 填写有效时长
    @IBAction func handleInputEffectiveDurationEvent(_ sender: UITapGestureRecognizer) {
        showInputAlert(withTitle: "设置有效时长(s)") { (text) in
            self.effectiveDurationLabel.text = "\(text)s"
        }
    }
    // 发送/接受临时秘钥
    @IBAction func handleTempkeyEvent(_ sender: UIButton) {
        switch self.state {
        case 0:// 待领取
            WNLockApi.getTempKeyInfo(tempkeyId: self.tempKeyId ?? 0).execute { result in
                switch result {
                case .success:
                    HUD.flash(.label("领取成功"), delay: 1.5)
                case .failure(let error):
                    HUD.flash(.label(error.errMsg), delay: 1.5)
                }
            }
        case 1://待确认
            WNLockApi.getTempKeyInfo(tempkeyId: self.tempKeyId ?? 0).execute { result in
                switch result {
                case .success:
                    HUD.flash(.label("确认成功"), delay: 1.5)
                case .failure(let error):
                    HUD.flash(.label(error.errMsg), delay: 1.5)
                }
            }
            
        default://发送
            showInputAlert(withTitle: "设置电话号码") { (text) in
                WNLockApi.sendTempKey(parameters:
                    ["lockId": self.lock?.id ?? 0,
                     "tempKeyId": self.tempKeyId ?? 0,
                     "startTime": self.effectiveTimeLabel.text!,
                     "validTime": self.effectiveDurationLabel.text!,
                     "validCount": self.effectiveDurationLabel.text!,
                     "cc": "86",
                     "phone": text
                    ]).execute(completion: { result in
                        switch result {
                        case .success:
                            HUD.flash(.label("发送成功"), delay: 1.5)
                        case .failure(let error):
                            HUD.flash(.label(error.errMsg), delay: 1.5)
                        }
                    })
                
            }
        }
    }
    
    
    @objc private func handleDismissDatePickerEvent(_ sender: UITapGestureRecognizer) {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd hh:mm"
        let dateStr = formatter.string(from: Date())
        self.effectiveTimeLabel.text = dateStr
        sender.view?.removeFromSuperview()
    }
    @objc private func handleDataPickerValueChangedEvent(_ sender: UIDatePicker) {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd hh:mm"
        let dateStr = formatter.string(from: sender.date)
        self.effectiveTimeLabel.text = dateStr
    }
    /// 显示带有输入框的alert view
    private func showInputAlert(withTitle title: String, handler: @escaping (String) -> Void) {
        let alertController = UIAlertController(title: title, message: nil, preferredStyle: .alert)
        alertController.addAction(UIAlertAction(title: "确认", style: .default, handler: { (_) in
            handler(alertController.textFields?.first?.text ?? "")
        }))
        alertController.addAction(UIAlertAction(title: "取消", style: .cancel, handler: { (_) in
            
        }))
        alertController.addTextField { (textField) in
            
        }
        present(alertController, animated: true, completion: nil)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    

}
